package com.bilibili.netty.im.server;

import com.bilibili.netty.im.handler.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: rgs-study0project
 * @description: netty客户端
 * @author: Mr.Ren
 * @create: 2023-10-30 22:31
 **/
public class IMServer {

    public static Map<String, Channel> USER = new ConcurrentHashMap<String, Channel>(1024);

    public static void start() throws InterruptedException {

        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline
                                //http解码器
                                .addLast(new HttpServerCodec())
                                //http支持大数据
                                .addLast(new ChunkedWriteHandler())
                                //http消息聚合
                                .addLast(new HttpObjectAggregator(1024*64))
                                //webSocket通信
                                .addLast(new WebSocketServerProtocolHandler("/"))
                                //自定义接收消息处理
                                .addLast(new WebSocketHandler());

                    }
                });

       bootstrap.bind(9985).sync();


    }
}
